package com.jianying.exer;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * ClassName: SideStreamTest
 * Package: com.atguigu.exer
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/10 15:55
 * @Version: 1.0
 */
public class SideStreamTest {
    public static void main(String[] args) throws Exception {
        // TODO 将水位线小于30的从主流输出到topic2  将水位线大于等于30的从侧输出流输出到topic3
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> wsDS = env.socketTextStream("localhost", 8888);
        OutputTag<String> outputTag = new OutputTag<String>("greater30") {};

        SingleOutputStreamOperator<String> processDS = wsDS.process(
                new ProcessFunction<String, String>() {
                    @Override
                    public void processElement(String value, ProcessFunction<String, String>.Context ctx, Collector<String> out) throws Exception {
                        String[] words = value.split(",");
                        int vc = Integer.parseInt(words[2]);
                        if (vc >= 30) {
                            ctx.output(outputTag, value);
                        } else {
                            out.collect(value);
                        }
                    }
                }
        );


        SideOutputDataStream<String> sideOutputDS = processDS.getSideOutput(outputTag);

        KafkaSink<String> firstSink = KafkaSink.<String>builder()
                .setBootstrapServers("localhost:9092,localhost:9093,localhost:9094")
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        .setTopic("first")
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build())
                .build();

        processDS.sinkTo(firstSink);



        KafkaSink<String> secondSink = KafkaSink.<String>builder()
                .setBootstrapServers("localhost:9092,localhost:9093,localhost:9094")
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        .setTopic("second")
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build())
                .build();

        sideOutputDS.sinkTo(secondSink);

        env.execute();
    }
}
